
package com.rt.schedulenew.service.impl;

import com.rt.schedulenew.api.IDictUsersService;
import com.rt.schedulenew.api.ITokenService;
import com.rt.schedulenew.utils.jwt.common.JwtToken;
import com.rt.schedulenew.utils.base.RequestUtil;
import com.rt.schedulenew.utils.jwt.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import com.rt.schedulebase.dto.DictUsersDto;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TokenServiceImpl implements ITokenService {
    @Autowired
    IDictUsersService dictUsersService;

    @Override
    public DictUsersDto getCurrentUser(final HttpServletRequest req) {
        DictUsersDto dictUsersDto = new DictUsersDto();
        final String token = req.getHeader("token");
        final String userId = req.getParameter("userId");
        final String userName = req.getParameter("userName");
        final String staffNo = req.getParameter("staffNo");
        final String deviceId = req.getParameter("deviceId");
        if (StringUtils.isNotBlank(userId) || StringUtils.isNotBlank(userName) || StringUtils.isNotBlank(staffNo)) {
            dictUsersDto.setUserId(userId);
            dictUsersDto.setName(userName);
            dictUsersDto.setStaffNo(staffNo);
            if (StringUtils.isBlank(userName)) {
                dictUsersDto.setName(userId);
            }
            if (StringUtils.isNotBlank(deviceId)) {
                dictUsersDto.setIpAddress(deviceId);
            }
        } else {
            final JwtToken.Payload payload = JwtTokenUtil.getPayloadInfo(token);
            dictUsersDto = this.dictUsersService.getUserInfo(payload.getUserId());
            dictUsersDto.setIpAddress(RequestUtil.getRemoteAddr(req));
        }
        return dictUsersDto;
    }
}
